package sebjul.ecom.dao;

import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Singleton;
import javax.persistence.*;
import java.util.*;

import sebjul.ecom.entities.*;


@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@SuppressWarnings("unchecked")
public class ArticleDao {

	@PersistenceContext
	EntityManager em;
	
	public Article createArticle(Article article) {
		em.persist(article);
		return article;
	}
	
	public  Article findArticleById (int id) {
		return em.find(Article.class, id);
	}
	
	public List<Article> findArticles() {
		Query query = em.createNamedQuery("findAllArticles");
		
		return query.getResultList();
	}
	
	public int countArticles() {
		Query query = em.createNamedQuery("countArticles");
		return query.getSingleResult().hashCode();
	}
	
	public List<Article> findArticleGenre(int idgenre, int begin, int end){
		return em.createNamedQuery("test2")
		  .setParameter("genreid", idgenre)
		  .setFirstResult(begin)
		  .setMaxResults(end)
		  .getResultList();
	}
	public int countArticleGenre(int idgenre){
		return em.createNamedQuery("countgenre")
		  .setParameter("genreid", idgenre)		  
		  .getSingleResult().hashCode();
	}
	
	
	
	public List<Article> findArticleByPage(int begin,int end){
		Query query = em.createNamedQuery("findAllArticlesByPage");
		query.setFirstResult(begin);
		query.setMaxResults(end);
		return query.getResultList();
	}
	
	public void deleteArticle(Article article) {
		em.remove(em.merge(article));
	}
	
	public Article updateArticle(Article article) {
		return em.merge(article);
	}
	
}
